<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="queryParams" ref="queryParamsRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="目录编码/名称" prop="name">
          <el-input
              v-model="queryParams.name"
              placeholder="请输入目录编码/名称"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="上传状态" prop="upload_flag">
          <el-select v-model="queryParams.upload_flag" placeholder="请选择上传状态" class="width-120" clearable>
            <el-option
                v-for="item in statusDict"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="退货日期">
          <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                          range-separator="截止" start-placeholder="开始日期" type="datetimerange"
                          value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            @click="upload"
            v-hasPerm="['msip:essSaleUndo:upload']"
        >
          <template #icon>
            <i-ep-upload/>
          </template>
          上传
        </el-button>
      </el-col>
    </el-row>

    <el-table v-adaptive :data="essSaleList" :border="true" :stripe="true" style="height: calc(100vh - 320px)"
              highlight-current-row @selection-change="handleSelectionChange" :header-cell-style="$headerCellStyle">
      <el-table-column type="selection" width="55" :align="'center'"/>
      <el-table-column label="销售退货ID" :align="'center'" prop="his_commodity_id" v-if="false"/>
      <el-table-column label="目录编码" :align="'center'" prop="fixmedins_hilist_id"/>
      <el-table-column label="目录名称" :align="'center'" prop="fixmedins_hilist_name" width="180"/>
      <el-table-column label="生产日期" :align="'center'" prop="manu_date" width="120">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.manu_date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期止" :align="'center'" prop="expy_end" width="120">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.expy_end, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批号" :align="'center'" prop="fixmedins_bchno"/>
      <el-table-column label="成交单价" :align="'center'" prop="finl_trns_pric"/>
      <el-table-column label="退货数量" :align="'center'" prop="sel_retn_cnt"/>
      <el-table-column label="退货日期" :align="'center'" prop="sel_retn_time" width="180">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.sel_retn_time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传状态" :align="'center'" prop="status">
        <template #default="scope">
          <el-tag
              :style="scope.row.status == '0' ? 'background-color: #02a30f; color: #fff; font-weight: bold;' : 'background-color: #c70505; color: #fff; font-weight: bold;'">
            {{ getUploadFlagLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="追溯码集合" :align="'center'" prop="drugtracinfo" show-overflow-tooltip width="180">
        <template #default="scope">
          <span v-for="(item, index) in scope.row.drugtracinfo" :key="index">
          {{ item.drug_trac_codg + ';' }}
        </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" :align="'center'" class-name="small-padding fixed-width" width="220">
        <template #default="scope">
          <el-button
              type="warning"
              @click="upload(scope.row)"
              v-hasPerm="['msip:essSaleUndo:upload']"
          >
            <template #icon>
              <i-ep-upload/>
            </template>
            上传
          </el-button>
          <el-button
              v-if="scope.row.status === '1'"
              type="danger"
              @click="viewErrorLog(scope.row)"
          >
            <template #icon>
              <i-ep-document/>
            </template>
            错误日志
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 错误弹出框 -->
    <el-dialog :close-on-click-modal="true" :title="title" v-model="open" width="40%" :fullscreen="false" class="custom-dialog">
      <el-form ref="formRef" :model="form" label-width="120px">
        <el-form-item label="返回参数" prop="resultsJson">
          <div class="param-container result-container">
            <pre class="param-content">
              {{ tryParseJSON(form.resultsJson) }}
            </pre>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default {
  name: "SaleUndo"
}
</script>

<script setup lang="ts">
import {saleUndoUpload, selectSaleUndoPage,errorLog} from "@/api/msip/ess.ts";
import {useUserStoreHook} from "@/store/modules/user.ts";
import {ElMessage} from "element-plus";

export interface Ess extends PageQuery {
  name: string,
  upload_flag: string,
  settle_start_date: string,
  settle_end_date: string,
  org_id: string,
}

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const statusDict = [
  {label: '未上传', value: '-1'},
  {label: '上传失败', value: '1'},
  {label: '已上传', value: '0'},
];
const {proxy} = getCurrentInstance() as any;
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth();
// 创建一个表示当月第一天的Date对象
const begin = proxy.$parseTime(new Date(year, month, 1), "{y}-{m}-{d} ");
const end = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([begin + "00:00:00", end + "23:59:59"]);
const formRef = ref();
const open = ref(false);
const title = ref("");
const queryParamsRef = ref()
const essSaleList = ref([]);
const showSearch = ref(true);
const his_commodity_ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const data = ref({
  form: {
    resultsJson: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: "",
    upload_flag: "-1",
    settle_start_date: "",
    settle_end_date: "",
    org_id: userInfo.orgId,
    records: ["住院退药", "门诊处方退药"]
  },
});

const {queryParams,form} = toRefs(data.value);

/** 查询进销存销售退货列表 */
function getList() {
  if (null != dateRange && '' != dateRange) {
    queryParams.value.settle_start_date = dateRange.value[0];
    queryParams.value.settle_end_date = dateRange.value[1];
  }
  selectSaleUndoPage(queryParams.value).then((response: any) => {
    essSaleList.value = response.rows;
    total.value = response.total;
  });
}

const getUploadFlagLabel = (statusValue) => {
  const found = statusDict.find(item => item.value == statusValue);
  return found ? found.label : statusValue;
}

// 表单重置
function reset() {
  nextTick(() => {
    formRef.value.resetFields()
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  // proxy.resetForm("queryRef");
  handleQuery();
}

// 取消按钮
function cancel() {
  open.value = false;
}
// 多选框选中数据
function handleSelectionChange(selection) {
  his_commodity_ids.value = selection.map(item => item.his_commodity_id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 上传按钮操作 */
function upload(row) {
  const _ids =  convertToArray(row.his_commodity_id || his_commodity_ids.value);
  let param = {
    his_commodity_ids: _ids,
    org_id: userInfo.orgId,
  };
  saleUndoUpload(param).then((res: any) => {
    if (res && res.code === 200) {
      ElMessage.success("上传成功");
      getList();
    } else {
      return ElMessage.error(res.msg)
    }
  });
}

/** 查询错误日志操作 */
function viewErrorLog(row) {
  let param = {
    hisMdtrtId: row.his_commodity_id,
    type: "3506",
    status: row.status,
    orgId: userInfo.orgId,
  };
  errorLog(param).then((res: any) => {
    if (res && res.code === 200) {
      open.value = true;
      title.value = "错误信息";
      form.value = res.data;
    } else {
      return ElMessage.error(res.msg)
    }
  });
}

function convertToArray(value) {
  if (value === null || value === undefined) {
    return [];
  }
  if (typeof value === 'string') {
    return value.split(',').map(String); // 将字符串按逗号分隔，并转换为数字数组
  }
  return value;
}
// 新增 tryParseJSON 方法
const tryParseJSON = (jsonString: string) => {
  try {
    return JSON.stringify(JSON.parse(jsonString), null, 2);
  } catch (e) {
    return jsonString;
  }
};

defineExpose({
  handleQuery
})

</script>

<style scoped>
.line {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

:deep(.string) {
  color: green;
}

:deep(.number) {
  color: darkorange;
}

:deep(.boolean) {
  color: blue;
}

:deep(.null) {
  color: magenta;
}

:deep(.key) {
  color: red;
}

.custom-dialog {
  padding: 20px;
}

.param-container {
  border: 1px solid #ebeef5;
  padding: 15px;
  border-radius: 4px;
  background-color: #e5edeb;
  height: 40vh;
  width: 100%;
  overflow: auto;
}

.result-container {
  height: 40vh;
  width: 100%;
}

.param-content {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>
